/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.manager.controler;

import com.sun.management.OperatingSystemMXBean;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.asiainfo.ability.base.utils.ExceptionUtils;
import org.asiainfo.ability.base.utils.JsonUtils;
import org.asiainfo.ability.base.utils.StringUtils;
import org.asiainfo.ability.base.code.InstanceState;
import org.asiainfo.ability.gateway.model.Ability;
import org.asiainfo.ability.gateway.vo.Page;
import org.asiainfo.ability.manager.code.PackageState;
import org.asiainfo.ability.manager.dao.PackageDao;
import org.asiainfo.ability.manager.model.JarPackage;
import org.asiainfo.ability.manager.service.PackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: visen
 * @Date: 2018/3/12
 * @Description:
 */
@RestController
public class PackageControler extends BaseControler {


    @Autowired
    private PackageService packageService;

    @Autowired
    private PackageDao packageDao;

    public static void copyInputStreamToFile(MultipartFile jarFile, File destination) throws IOException {
        InputStream source = jarFile.getInputStream();
        FileOutputStream fs = new FileOutputStream(destination);
        try {
            IOUtils.copy(source, fs);
            fs.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fs.close();
            source.close();
        }

    }

    @RequestMapping(value = "/package/commit", method = RequestMethod.POST)
    public void commitPackage(@RequestBody JarPackage jarPackage, HttpServletRequest request, HttpServletResponse response){
        jarPackage.setState(PackageState.commited);
        String branch = request.getParameter("branch");
        if(!StringUtils.isBlank(branch) && !branch.equals(jarPackage.getBranch())) {
            File file = new File(packageService.getRealJarPath(jarPackage)
                    +jarPackage.getJarName());
            jarPackage.setBranch(branch);
            file.renameTo(new File(packageService.getRealJarPath(jarPackage)
                    +jarPackage.getJarName()));

        }
        try {
            packageService.commitPackage(jarPackage);
        } catch (Exception e ){
            ExceptionUtils.logTrace(logger, e);
            returnResponse(response, "0");
        }

    }
    @RequestMapping(value = "/package/add", method = RequestMethod.POST)
    public void addPackage(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        MultipartFile jarFile = ((MultipartHttpServletRequest) request).getFile("file");
        File tempRemoteFile = null;
        JarPackage jarPackage = null;
        try {
            tempRemoteFile = new File(PackageService.REPOPATH);
            if(!tempRemoteFile.exists()) {
                tempRemoteFile.mkdir();
            }
            tempRemoteFile = new File(PackageService.REPOPATH, jarFile.getOriginalFilename());
            copyInputStreamToFile(jarFile, tempRemoteFile);
            jarPackage = packageService.readPackageInfo(tempRemoteFile);

            if(jarPackage == null) {
                tempRemoteFile.delete();
                returnResponse(response, "0");
                return;
            } else {
                packageService.addPackage(jarPackage);
                tempRemoteFile.renameTo(new File(packageService.getRealJarPath(jarPackage)
                        +jarPackage.getJarName()));
            }

        } catch (Exception e) {
            returnResponse(response, "0");
            if(tempRemoteFile != null && tempRemoteFile.exists()) {
                tempRemoteFile.delete();
            }
            ExceptionUtils.logTrace(logger, e);
            return;
        }
        returnResponse(response, JsonUtils.toJSON(jarPackage));
    }

    @RequestMapping(value = "/package", method = RequestMethod.GET)
    public @ResponseBody String listPackages(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String serviceName = request.getParameter("sn");
        Page page = new Page();
        try {
            page.setPage(Integer.parseInt(request.getParameter("page")));
            page.setLimit(Integer.parseInt(request.getParameter("limit")));
            page.setPage((page.getPage()-1) * page.getLimit());
        } catch (Exception e){}

        return JsonUtils.toJSON(packageService.listRepoViewData(serviceName, page));
    }

    @RequestMapping(value = "/package/{id}", method = RequestMethod.DELETE)
    public void deletePackage(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
        try {
            packageService.deletePackage(id);
        } catch (Exception e) {
            returnResponse(response, "0");
        }
    }

    public static void main(String[] args) throws Exception{

        File f = new File("D:\\cloud\\esap\\repos\\abc\\2018-03-14-11-15-13-11154\\a1.txt");

        PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f)));
        pw.write("aaabbb");
        pw.close();

    }

}
